package com.hbnu.mysql.User;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/*
 * @description: 注册登录功能
 * @author zouting
 * @Date 2025-11-04-16:41
 *
 */public class  LoginService extends LRService {

    // 新增返回码
    public static final int OK = 0;
    public static final int WRONG_PASSWORD = 1;
    public static final int USER_NOT_EXIST = 2;
//    public static void main(String[] args) {
//        //1.给用户提供登录的界面（入口）
//        Scanner scanner = new Scanner(System.in);
//        Map<String, String> userInfo = initUI(scanner);
//        //2.校验用户输入的账号和密码
//        boolean result = verifiedUserInfo(userInfo);
//        System.out.println(result ? "登录成功" : "登录失败");
//    }

    /**
     * 初始化用户界面，获取用户输入的用户名和密码
     *
     * @return 包含用户名和密码的Map集合
     */
    @Override
    public Map<String, String> initUI(Scanner scanner) {

        Map<String, String> userInfo = new HashMap<>();

        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        userInfo.put("username", username);
        userInfo.put("password", password);

        return userInfo;
    }


    //验证用户信息
//    Connection connection = DriverManager.getConnection(url, user, pwd);URL,USER,PWD是私有成员子类无法直接访问
    /*
     * @return 0:成功 ; 1 密码错误 ; 2 用户不存在
     * */
    @Override
    public int verifiedUserInfo(Map<String, String> userInfo) {


        String username = userInfo.get("username");
        String password = userInfo.get("password");

        //添加管理员信息--判断用户是否为管理员帐号，是则标记为管理员---p98
        if (username.equals("admin") && password.equals("admin")) {
            userInfo.put("isAdmin", "true");
            return OK;
        }

        //查库中查询用户信息
        String sql = "select password,role from tb_user where username = ?";//按用户名查询
        try (Connection connection = LRService.getConnection();// 使用父类的 getConnection 方法
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setString(1, username);
//            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (!resultSet.next()) {
                return USER_NOT_EXIST;
            }
            if (!password.equals(resultSet.getString("password"))) {
                return WRONG_PASSWORD;
            }


//            try (ResultSet resultSet = preparedStatement.executeQuery()) {
////                return resultSet.next(); // 如果有匹配的用户记录则返回true
            //验证用户信息，数据库字段role==1则标记为管理员
            int role = resultSet.getInt("role");
            if (role == 1) {
                userInfo.put("isAdmin", "true");
            }
            return OK;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;//异常
    }

    //检查用户是否为管理员
    public boolean isAdmin(Map<String, String> userInfo) {
        return "true".equals(userInfo.get("isAdmin"));
    }


    //管理员
    public void adminMenu(Scanner scanner) {
        while (true) {
            System.out.println("\n========== 管理员菜单 ==========");
            System.out.println("1. 查看所有用户信息");
            System.out.println("2. 删除用户");
            System.out.println("3. 修改用户信息");
            System.out.println("4. 查看所有订单");
            System.out.println("5. 退出管理员菜单");
            System.out.print("请选择操作(1-5): ");

            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    showAllUsers();
                    break;
                case "2":
                    deleteUser(scanner);
                    break;
                case "3":
                    updateUser(scanner);
                    break;
                case "4":
                    showAllOrders();
                    break;
                case "5":
                    System.out.println("退出管理员菜单");
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
                    break;
            }
        }
    }

    //管理员可以查看所有用户信息

    /**
     * 查看所有用户信息
     */
    private void showAllUsers() {
        String sql = "SELECT id, username, address, phone, role FROM tb_user";
        try (Connection connection = LRService.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            System.out.println("========== 所有用户信息 ==========");
            System.out.printf("%-10s %-15s %-20s %-15s %-8s\n",
                    "用户ID", "用户名", "地址", "手机号", "角色");
            System.out.println("---------------------------------------------------------------------------");

            while (resultSet.next()) {
                String role = resultSet.getInt("role") == 1 ? "管理员" : "普通用户";
                System.out.printf("%-10d %-15s %-20s %-15s %-8s\n",
                        resultSet.getInt("id"),
                        resultSet.getString("username"),
                        resultSet.getString("address"),
                        resultSet.getString("phone"),
                        role);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户
     */
    private void deleteUser(Scanner scanner) {
        System.out.print("请输入要删除的用户名: ");
        String username = scanner.nextLine().trim();

        // 防止删除自己
        if ("admin".equals(username)) {
            System.out.println("不能删除管理员账号！");
            return;
        }

        String sql = "DELETE FROM tb_user WHERE username = ?";
        try (Connection connection = LRService.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setString(1, username);
            int rowsAffected = preparedStatement.executeUpdate();

            if (rowsAffected > 0) {
                System.out.println("用户 " + username + " 删除成功");
            } else {
                System.out.println("用户不存在或删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改用户信息
     */
    private void updateUser(Scanner scanner) {
        System.out.print("请输入要修改的用户名: ");
        String username = scanner.nextLine().trim();

        System.out.print("请输入新密码(直接回车保持原密码): ");
        String newPassword = scanner.nextLine().trim();

        System.out.print("请输入新地址(直接回车保持原地址): ");
        String newAddress = scanner.nextLine().trim();

        System.out.print("请输入新手机号(直接回车保持原手机号): ");
        String newPhone = scanner.nextLine().trim();

        System.out.print("是否设置为管理员? (y/n, 直接回车保持原角色): ");
        String roleInput = scanner.nextLine().trim();
        Integer newRole = null;
        if ("y".equalsIgnoreCase(roleInput)) {
            newRole = 1;
        } else if ("n".equalsIgnoreCase(roleInput)) {
            newRole = 0;
        }

        StringBuilder sql = new StringBuilder("UPDATE tb_user SET ");
        boolean needComma = false;

        if (!newPassword.isEmpty()) {
            sql.append("password = ?");
            needComma = true;
        }

        if (!newAddress.isEmpty()) {
            if (needComma) sql.append(", ");
            sql.append("address = ?");
            needComma = true;
        }

        if (!newPhone.isEmpty()) {
            if (needComma) sql.append(", ");
            sql.append("phone = ?");
            needComma = true;
        }

        if (newRole != null) {
            if (needComma) sql.append(", ");
            sql.append("role = ?");
        }

        sql.append(" WHERE username = ?");

        try (Connection connection = LRService.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql.toString())) {

            int paramIndex = 1;
            if (!newPassword.isEmpty()) {
                preparedStatement.setString(paramIndex++, newPassword);
            }
            if (!newAddress.isEmpty()) {
                preparedStatement.setString(paramIndex++, newAddress);
            }
            if (!newPhone.isEmpty()) {
                preparedStatement.setString(paramIndex++, newPhone);
            }
            if (newRole != null) {
                preparedStatement.setInt(paramIndex++, newRole);
            }
            preparedStatement.setString(paramIndex, username);

            int rowsAffected = preparedStatement.executeUpdate();
            if (rowsAffected > 0) {
                System.out.println("用户信息更新成功");
            } else {
                System.out.println("用户不存在或更新失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //查看所有订单
    private void showAllOrders() {
        String sql = "SELECT o.order_id, o.username, o.total_amount, o.status, " +
                "o.create_time, o.address, o.phone " +
                "FROM tb_orders o " +
                "ORDER BY o.create_time DESC";

        try (Connection connection = LRService.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {

            System.out.println("\n========== 所有订单信息 ==========");
            System.out.printf("%-10s %-15s %-12s %-10s %-20s %-15s\n",
                    "订单号", "用户名", "总金额", "状态", "创建时间", "联系电话");
            System.out.println("-------------------------------------------------------------------------------------------");

            boolean hasOrders = false;
            while (resultSet.next()) {
                hasOrders = true;
                System.out.printf("%-10d %-15s %-12.2f %-10s %-20s %-15s\n",
                        resultSet.getInt("order_id"),
                        resultSet.getString("username"),
                        resultSet.getDouble("total_amount"),
                        resultSet.getString("status"),
                        resultSet.getTimestamp("create_time").toString().substring(0, 16),
                        resultSet.getString("phone"));
            }

            if (!hasOrders) {
                System.out.println("暂无订单数据");
            }

        } catch (Exception e) {
            System.out.println("获取订单信息失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

}

